<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Relations\ValidateTrait;
use Illuminate\Support\Facades\DB;
use App\Models\Relations\UserInfoTrait;
class Employ extends Model
{
    use SoftDeletes,ValidateTrait,UserInfoTrait;
    
    protected $table="employ";
    
    protected $fillable = ['id','title','cat_id','thumb','description','content','from','tags','pagination_type','from',
        'status','user_id','display_order','top','is_recommond','exam_id','is_validate','validated_at','to_link'
    ];
    
    protected $dates = ['deleted_at','validated_at'];
    
    /**
     * 
     * 新闻与缩略图 一对一关联
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function attachment()
    {
        return $this->hasOne('App\Models\Attachment','aid','thumb');
    }
    
    /**
     * 新闻与标签关联表  一对多关联
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function tags()
    {
        return $this->hasMany('App\Models\TagsNews','news_id','id');
    }
    
    /**
     * 新闻与分类 一对一关联
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function category()
    {
        return $this->hasOne('App\Models\Category','cat_id','cat_id');
    }
    
    /**
     * 新闻与扩展信息 关联  一对一
     */
    public function exts()
    {
        return $this->hasOne('App\Models\EmployExt','news_id','id');
    }
	 /**
     * 评论信息 关联  一对多
     */
	public function comments()
	{
		return $this->hasMany('App\Models\EmployComments','employ_id','id');
	}

    /**
     * 获取相关试卷
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function examination()
    {
        return $this->hasOne('App\Models\Examination','id','exam_id');
    }

	/**
	 * 获取列表数据
	 */
	public function getList($limit,$page,$category,$sort = 0)
	{
	    $query = DB::table($this->table)
	       ->leftJoin('employ_ext','employ.id','=','employ_ext.news_id')
	       ->leftJoin('users','employ.user_id','=','users.id')
	       ->leftJoin('attachment','employ.thumb','=','attachment.aid')
	       ->select('employ.*','employ_ext.*','users.name as user_name','attachment.url');
	       
	    if(!empty($category))
	    {
	        $query->whereIn('cat_id',$category);
	    }
	    $query->where('is_validate','=',1);
	    switch ($sort){
	        case 1:
	            $query->orderBy('employ_ext.reading_num','desc');break;
	        case 2:
	            $query->orderBy('employ_ext.comment_num','desc');break;
	        case 3:
	            $query->orderBy('employ_ext.recommond_num','desc');break;
            default:
                $query->orderBy('employ_ext.reading_num','desc')->orderBy('employ_ext.comment_num','desc')->orderBy('employ_ext.recommond_num','desc');
                
	    }
	    $result = $query->orderBy('updated_at','desc')->skip($limit)->take($page)->get();
	    
	    return $result;
	        
	}
}